package leetcode.onehundred;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;

import java.util.LinkedList;
import java.util.Queue;

//翻转二叉树
public class InvertTree {

    //递归
    public TreeNode invertTree1(TreeNode root) {
        if (root == null) {
            return null;
        }
        //交换当前结点的左右子树
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;

        //递归交换当前结点的左子树
        invertTree1(root.left);
        //递归交换当前结点的右子树
        invertTree1(root.right);

        //走到这里时，说明已经交换完毕
        return root;
    }

    //BFS
    public TreeNode invertTree2(TreeNode root) {
        if (root == null) {
            return null;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
        return root;
    }
}
